﻿using GrainManage.Web.Models.Account;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GrainManage.Entities.Account;
using GrainManage.Web.Resources;
using GrainManage.Web.Common;
using GrainManage.Web.Models;

namespace GrainManage.Web.Controllers
{
    public class AccountController : BaseController
    {
        [AllowAnonymous]
        public ActionResult Login(string targetName)
        {
            var loginModel = new LoginModel { SignIn = new SignInModel(), Registration = new RegisterModel() };
            if (!string.Equals(targetName, "Register", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    if (!string.IsNullOrEmpty(Utils.GetCookie(Constant.CookieName)))
                    {
                        var isChecked = Convert.ToBoolean(Utils.GetCookie(Constant.CookieName, "RememberMe"));
                        if (isChecked)
                        {
                            var input = loginModel.SignIn;
                            input.RememberMe = isChecked;
                            input.UserName = Utils.GetCookie(Constant.CookieName, "UserName");
                            input.Password = Utils.GetCookie(Constant.CookieName, "Password");
                            input.EncryptFlag = (GrainManage.Entities.Encrypt.EncryptFlag)int.Parse(Utils.GetCookie(Constant.CookieName, "EncryptFlag"));
                        }
                    }
                }
                catch (Exception)
                {
                    Utils.DeleteCookie(Constant.CookieName);
                }

                return View("SignIn", loginModel.SignIn);
            }
            else
            {
                return View("Register", loginModel.Registration);
            }
        }

        [AllowAnonymous]
        public ActionResult ResetPassword()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult SignOut()
        {
            var inputPara = new InputSignOut
            {
                Authentication = CurrentAccount
            };
            var accountProxy = ObjectFactory.AccountProxy;
            var result = accountProxy.SignOut(inputPara);
            if (Request.IsAjaxRequest())
            {
                return NewtonsoftJson(result);
            }
            return View("SignIn", new SignInModel { UserName = inputPara.Authentication.UserName });
        }

        //******************************************************POST******************************************************

        [AllowAnonymous]
        [HttpPost]
        public ActionResult SignIn(SignInModel input)
        {
            if (!ModelState.IsValid)
            {
                return View(input);
            }

            var inputPara = new InputSignIn
            {
                UserName = input.UserName,
                Password = input.Password,
                EncryptModel = input.EncryptFlag
            };
            var accountProxy = ObjectFactory.AccountProxy;
            var result = accountProxy.SignIn(inputPara);
            if (result.Status.StatusCode == 1)
            {
                bool isRemember = input.RememberMe;
                //写入Cookies
                if (isRemember)
                {
                    Utils.WriteCookie(Constant.CookieName, "RememberMe", Convert.ToString(isRemember), 14400);
                    Utils.WriteCookie(Constant.CookieName, "UserName", input.UserName);
                    Utils.WriteCookie(Constant.CookieName, "Password", input.Password);
                    Utils.WriteCookie(Constant.CookieName, "EncryptFlag", ((int)input.EncryptFlag).ToString());
                }
                else
                {
                    Utils.DeleteCookie(Constant.CookieName);
                }
                CurrentAccount = new Entities.AppInfo { UserName = input.UserName, Guid = result.Guid, LoginIP = RequestHelper.GetIP() };
                return RedirectToAction("SearchContacts", "Contact");
            }
            else
            {
                ViewBag.Result = result;
                return View(input);
            }
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Register(RegisterModel input)
        {
            if (!ModelState.IsValid)
            {
                return View(input);
            }

            var inputPara = new InputRegister
            {
                Account = new Data.Model.Form.RegisterForm
                {
                    UserName = input.UserName,
                    CellPhone = input.CellPhone,
                    CheckLoginIP = input.CheckLoginIP,
                    Email = input.EmailAddress,
                    Password = input.Password,
                    RealName = input.RealName,
                    Remarks = input.Remarks
                },

                EncryptModel = input.EncryptFlag
            };
            var accountProxy = ObjectFactory.AccountProxy;
            var result = accountProxy.Register(inputPara);
            if (result.Status.StatusCode == 1)
            {
                var manage = new InputManageAccount
                {
                    Authentication = CurrentAccount,
                    Account = new Data.Model.Form.ManageForm
                    {
                        AccountName = input.UserName,
                        IsApproved = true,
                        PermissionID = 4
                    }
                };
                accountProxy.ManageAccount(manage);
                return RedirectToAction("SignIn", new InputSignIn { UserName = input.UserName, Password = input.Password, });
            }
            else
            {
                ViewBag.Result = result;
                return View(input);
            }
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult ResetPassword(ResetPasswordModel input)
        {
            if (!ModelState.IsValid)
            {
                return View(input);
            }

            var inputPara = new InputResetPassword
            {
                Email = input.EmailAddress,
                UserName = input.UserName
            };
            var accountProxy = ObjectFactory.AccountProxy;
            var result = accountProxy.ResetPassword(inputPara);
            if (Request.IsAjaxRequest())
            {
                return NewtonsoftJson(result);
            }
            return View(Constant.RestStatusView, result);
        }

        [HttpPost]
        public ActionResult ManageAccount(ManageAccountModel input)
        {
            if (!ModelState.IsValid)
            {
                return View(input);
            }

            var inputPara = new InputManageAccount
            {
                Authentication = CurrentAccount,
                Account = new Data.Model.Form.ManageForm
                {
                    AccountName = input.AccountName,
                    IsApproved = input.IsApproved,
                    PermissionID = input.PermissionID
                }
            };
            var accountProxy = ObjectFactory.AccountProxy;
            var result = accountProxy.ManageAccount(inputPara);
            if (Request.IsAjaxRequest())
            {
                return NewtonsoftJson(result);
            }
            return View(Constant.RestStatusView, result);
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel input)
        {
            if (!ModelState.IsValid)
            {
                return View(input);
            }

            var inputPara = new InputChangePassword
            {
                Authentication = CurrentAccount,
                EncryptModel = input.EncryptFlag,
                NewPassword = input.NewPassword,
                OldPassword = input.OldPassword
            };
            var accountProxy = ObjectFactory.AccountProxy;
            var result = accountProxy.ChangePassword(inputPara);
            if (Request.IsAjaxRequest())
            {
                return NewtonsoftJson(result);
            }
            return View(Constant.RestStatusView, result);

        }
    }
}
